import styled from 'styled-components';
import React, { CSSProperties, useCallback, useEffect, useState } from 'react';
import { Input, Button as AntdButton, Tree, Collapse, Modal, Drawer } from 'antd';
import { PlusOutlined, TableOutlined, UnorderedListOutlined, SettingOutlined, DatabaseOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import type { CollapseProps } from 'antd';
import { MetaDataDomain, metaDataGetMetaDataObjects, metaDataGetMetaDatas, metaDataSaveDomain } from '../../../services';
import { DomainEditor, DomainImporter, MetaDataObjectPanel, MetaDataDomainPanel, DataDomainTable } from '.';
import { dsFind, ComparsionOperator } from '@/services/local';
import { CLASS_CLASS_IDENTIFIER, DOMAIN_CLASS_IDENTIFIER, DOMAIN_CLASS_NAME } from '@/services/constants';

const { Search } = Input;

export interface DomainCategoryTreeProps {
    style?: CSSProperties;
    onDomainSelected: (domainIdentifier: string | null) => Promise<void>;
    onSelected: (type: 'root' | 'domain' | 'object' | string, node: any) => Promise<void>;
    version: number;
}

export const DomainCategoryTree: React.FC<DomainCategoryTreeProps> = (props) => {

    const [isModalOpen, setIsModalOpen] = useState(false);

    const [domainMgrOpen, setDomainMgrOpen] = useState<boolean>(false);

    const [filter, setFilter] = useState<string>('');

    const [domains, setDomains] = useState<Array<MetaDataDomain>>([]);

    const [domainIdentifier, setDomainIdentifier] = useState<string | null>(null);

    const [objectIdentifier, setObjectIdentifier] = useState<string | null>(null);

    const navigate = useNavigate();

    const refresh = async () => {
        try {
            let res = await dsFind(0, DOMAIN_CLASS_IDENTIFIER, {});
            //
            setDomains(res.data);
        } catch (error) {
            console.error(error);
        }
    };
    useEffect(() => {
        refresh();
    }, [props.version]);

    useEffect(() => {
        if (domains && domains.length > 0) {
            //
            if (domainIdentifier === null) {
                setDomainIdentifier(domains[0].identifier);
            } else {
                //判断是否存在
                let exist = false;
                for (let i = 0; i < domains.length; i++) {
                    if (domainIdentifier === domains[i].identifier) {
                        exist = true;
                        break;
                    }
                }
                if (!exist && domainIdentifier !== null) {
                    setDomainIdentifier(null);
                }
            }
        } else {
            setDomainIdentifier(null);
        }
    }, [domains]);

    useEffect(() => {
        props.onDomainSelected && props.onDomainSelected(domainIdentifier);
    }, [domainIdentifier]);

    return (
        <Container style={props.style}>
            <Header>
                <AddButton>
                    <AntdButton
                        icon={<UnorderedListOutlined />}
                        onClick={async () => {
                            setDomainMgrOpen(true);
                        }}
                    ></AntdButton>
                </AddButton>
                <Search
                    style={{
                        flex: 1
                    }}
                    styles={{}}
                    placeholder="Filter"
                    allowClear={true}
                    onChange={(event) => {
                        setFilter(event.target.value);
                    }} onSearch={(value) => {
                        setFilter(value);
                    }} />
                <AddButton>
                    <AntdButton
                        icon={<PlusOutlined />}
                        onClick={async () => {
                            setIsModalOpen(true);
                        }}
                    ></AntdButton>
                </AddButton>
            </Header>
            <CollapseContainer>
                <Collapse
                    accordion={true}
                    bordered={false}
                    activeKey={[domainIdentifier]}
                    onChange={async (keys) => {
                        console.log(keys);
                        if (keys && keys.length > 0) {
                            setDomainIdentifier(keys[0]);
                        } else {
                            setDomainIdentifier(null);
                        }
                    }}
                    expandIconPosition={"start"}
                    destroyInactivePanel={false}
                    items={domains.map((domain, index) => {
                        return {
                            key: domain.identifier,
                            label: domain.title,
                            children: <DomainTree key={index}
                                filter={filter}
                                onSelect={async (key: string | null, node: CategoryTreeNode | null) => {
                                    props.onSelected && await props.onSelected(key, node);
                                }} domain={domain}
                            ></DomainTree>,
                            styles: {
                                body: {
                                    padding: '0'
                                }
                            },
                            extra: <SettingOutlined
                                onClick={async (event) => {
                                    props.onDomainSelected && await props.onDomainSelected(domainIdentifier);
                                    event.stopPropagation();
                                }}
                            />
                        }
                    })}
                />
            </CollapseContainer>
            <Modal
                styles={{
                    content: {
                        minWidth: '600px',
                        minHeight: '400px'
                    }
                }}
                title="添加/导入域"
                footer={false}
                destroyOnClose={true}
                open={isModalOpen}
                onOk={() => {
                    setIsModalOpen(false);
                }} onCancel={() => {
                    setIsModalOpen(false);
                }}>
                <DomainImporter onFinish={async () => {
                    //
                    await refresh();
                    setIsModalOpen(false);
                }}></DomainImporter>
            </Modal>
            <Drawer
                title="域管理"
                onClose={async () => {
                    //刷新
                    await refresh();
                    setDomainMgrOpen(false);
                }}
                width={'calc(100% - 270px)'}
                destroyOnClose={true}
                open={domainMgrOpen}>
                <DataDomainTable></DataDomainTable>
            </Drawer>
        </Container>
    );
}



interface CategoryTreeNode {
    title: string;
    key: string;
    icon?: any;
    isLeaf?: boolean;
    children: CategoryTreeNode[];
}

const updateTreeData = (list: CategoryTreeNode[], key: React.Key, children: CategoryTreeNode[]): CategoryTreeNode[] =>
    list.map((node) => {
        if (node.key === key) {
            return {
                ...node,
                children,
            };
        }
        if (node.children) {
            return {
                ...node,
                children: updateTreeData(node.children, key, children),
            };
        }
        return node;
    });

export interface DomainTreeProps {
    style?: CSSProperties;
    domain: MetaDataDomain;
    filter: string;
    onSelect: (key: string | null, node: CategoryTreeNode | null) => Promise<void>;
}

const DomainTree: React.FC<DomainTreeProps> = (props) => {

    const [treeData, setTreeData] = useState<Array<CategoryTreeNode>>([]);

    const navigate = useNavigate();

    useEffect(() => {
        if (!props.domain || !props.domain.identifier) return;
        dsFind(0, CLASS_CLASS_IDENTIFIER, {
            attributes: [{
                name: 'domain_identifier',
                operator: ComparsionOperator.Equal,
                value: props.domain.identifier
            }]
        }).then((objs) => {
            setTreeData(objs.data.map((objItem, index) => {
                return {
                    title: objItem.title,
                    key: objItem.identifier,
                    icon: <TableOutlined />,
                    isLeaf: true,
                    children: []
                };
            }));
        });
    }, [props.domain]);

    return (
        <TreeContainer style={props.style}>
            <Tree
                showIcon={true}
                showLine={true}
                treeData={treeData.filter(item => item.title.indexOf(props.filter) >= 0)}
                defaultExpandAll={true}
                onSelect={async (selectedKeys, e: { selected: boolean, selectedNodes, node, event }) => {
                    console.log(selectedKeys, e);
                    if (selectedKeys && selectedKeys.length > 0) {
                        props.onSelect(selectedKeys[0] + '', e.node ? e.node : null);
                    } else {
                        props.onSelect(null, null);
                    }
                }}
            />
        </TreeContainer>
    );
}


const Container = styled.div`
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
`;

const Header = styled.div`
    height: 45px;
    width: 100%;
    padding: 0 0px;
    display: flex;
    background-color: #EFEFEF;
    align-items: center;
    justify-content: space-between;
`;

const AddButton = styled.div`
    width: 34px;
    display: flex;
    align-items: center;
    justify-content: center;
`;

const CollapseContainer = styled.div`
    flex: 1;
    width: 100%;
    overflow-y: auto;
    overflow-x: auto;
`;

const TreeContainer = styled.div`
    flex: 1;
    width: 100%;
`;